"""
    qsiauth.strategies.password
    ============================

    :copyright: (c) 2010 Google Inc.
    :license: Apache Software License, see LICENSE for details.
"""
from __future__ import absolute_import
from qsiauth import models
from qsiauth.strategies.base import BaseStrategy
from webapp2_extras import security



class WelcomeStrategy(BaseStrategy):

    def user_info(self, req):
        email = req.POST['email']
        user_info = req.POST.get('user_info', {})
        user_info['emails'] = [{'value': email, 'type': 'home', 'primary': True}]
        auth_id = models.User.generate_auth_id('welcome', email)
        return {
            'auth_id': auth_id,
            'info': user_info,
            'extra': {
                'raw_info': user_info,
                }
        }

    def get_profile(self, auth_id, **kwargs):
        """
        Overrides to provide logic for checking and encrypting  passwords.
        :param auth_id:
        :param user_info:
        :param kwargs:
        :return:
        :raise:
        """
        profile = models.UserProfile.get_by_id(auth_id)
        if profile is None:
            # Profile does not exist
            return self.raise_error('The account does not exists, check the email '
                                    'that you\'ve provided is correct.'
                                    'Please try again.')
        return profile

    def handle_request(self, req):
        # confirm that required fields are provided.
        password = req.POST['password']
        email = req.POST['email']
        self.validate_email(email)
        if not password:
            return self.raise_error('Please provide a password.')
        user_info = self.user_info(req)
        profile = self.get_profile(
            auth_id=user_info['auth_id'],
            user_info=user_info,
            password=password)
#        req.register_user_by_profile(profile)
        req.load_user_by_profile(profile)
        return req.get_redirect_uri()
